import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:app/components/index.dart';
import 'package:app/api/material-pick/index.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import '../../api/account/index.dart';


class Packing extends StatefulWidget{

  const Packing({super.key,});

  @override
  State<Packing> createState() => _PackingState();

}

class _PackingState extends State<Packing>{

  // 拣配单号
  String _pickCode = "";
  // 物料编号
  String _code = "";
  // 托盘号
  String _containerCode = "";
  // 位置
  String _station = "";

  String _pickId = "";
  //车间
  String _erpDeptCode = "";
  //出库单号
  String _billNo = "";

  final FocusNode _firstFocusNode = FocusNode();

  final FocusNode _secondFocusNode = FocusNode();

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      materialList();
      userInfo();
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  // 设置值
  void setValue(String key, String value){
    switch (key) {
      case '_code': setState(() => _code = value); break;
      case '_billNo': setState(() => _billNo = value); break;
      default:
        throw Exception("key error");
    }
  }

  void clear(){
    setState(() => _code = "");
  }

  List<dynamic> _list = [];

  /// 确认
  void confirm(){
    WidgetsBinding.instance.addPostFrameCallback((_){
      Forms.validate(_formKey!).then((valid) async {
        if(valid){
          MaterialPickApi.of(context).materialByCode(_code).then((res){
            if(StringUtils.isNotNull(res.data)){
              saveMaterial(res.data);
            }
          });
        }
      });
    });
  }

  /// 确认-涂装车间
  void painting(){
    Forms.validate(_formKey!).then((valid) async {
      if(valid){
        MaterialPickApi.of(context).materialByBill(_code,_billNo).then((res){
          if(StringUtils.isNotNull(res.data)){
            saveMaterial(res.data);
          }
        });
      }
    });
  }

  /// 获取用户信息
  userInfo(){
    Account.of(context).userInfo().then((res){
      if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)
          && StringUtils.isNotNull(res.data['data']['erpDeptCode'])){
        setState(() => _erpDeptCode = res.data['data']['erpDeptCode']);
      }
    });
  }

  /// 保存物料信息
  void saveMaterial(params){
    Map<String,dynamic> data = {
      'pickId': _pickId,
      'containerCode': _containerCode,
      'pickCode': _pickCode,
      'station': _station,
      'code': _code,
      // 'itemName': params['data']['name'],
      // 'itemUnit': params['data']['unit'],
      // 'itemQty': params['data']['number'],
      // 'itemCode': params['data']['code'],
      // 'erpInvBillCode': params['data']['otherBillNo'],
      // 'taskNo': params['data']['shopOrder'],
      // 'itemOpNo': params['data']['opNo'],
      // 'itemSeqNo': params['data']['seqNo'],
      ...params['data']
    };
    MaterialPickApi.of(context).save(data).then((res){
      if(StringUtils.isNotNull(res.data) && res.data['code'] == 'success'){
        materialList();
      }
    });
  }

  /// 物料列表
  void materialList(){
    MaterialPickApi.of(context).materialListByPickId(_pickId, _containerCode).then((res){
      if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
        setState(() => _list = res.data['data']);
        clear();
        FocusScope.of(context).requestFocus(_firstFocusNode);
      }
    });
  }

  /// 添加数量
  void add(index){
    final item = _list[index];
    final number = item['itemQty'] + 1;
    if(item['qty'] >= number){
      updateNumber(number, item);
    }
  }

  /// 修改数量
  void updateNumber(number, item){
    MaterialPickApi.of(context).updateItemQty({'itemQty': number, 'id': item['id']}).then((res){
      if(res.data['code'] == 'success'){
        setState(() => item['itemQty'] = number);
      }
    });
  }

  /// 减数量
  void subtraction(index){
    final item = _list[index];
    final number = item['itemQty'] > 1 ? item['itemQty'] - 1 : 0;
    if(number >= 1){
      updateNumber(number, item);
    }
  }

  /// 手动改变数量
  changeNumber(int index, String value){
    final item = _list[index];
    double number = value != '-' ? double.parse(value) : 0;
    if(number >= 1 && item['qty'] >= number){
      updateNumber(number, item);
    }
  }

  /// 删除
  void remove(index){
    Confirm.of(context).show('确定要删除么？', (){
      MaterialPickApi.of(context).removeMaterial(_list[index]['id']).then((res){
        if(res.data['code'] == 'success'){
          Navigator.of(context).pop();
          materialList();
        }
      });
    });
  }

  /// 设置参数
  void setParams(params){
    setState(() {
      _pickCode = params['pickCode'];
      _containerCode = params['containerCode'];
      _station = params['station']??"";
      _pickId = params['pickId'];
    });
  }

  @override
  Widget build(BuildContext context) {
    setParams(ModalRoute.of(context)!.settings.arguments);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '开始拣配'),
      body: GestureDetector(
          onTap: hideKeyBorder,
          child: Column(
            children: [
              Horizontal(
                items: [
                  HorizontalItem(
                    flex: 2,
                    label: '托  盘  号：',
                    value: _containerCode,
                    fontWeight: FontWeight.w600,
                  ),
                  HorizontalItem(
                    flex: 2,
                    label: '拣配单号：',
                    value: _pickCode,
                    fontWeight: FontWeight.w600,
                  ),
                ],
              ),
              Horizontal(
                  borderBottom: true,
                  items: [
                    HorizontalItem(
                    flex: 0,
                    label: '位        置：',
                    value: _station,
                    fontWeight: FontWeight.w600,
                    ),
                  ]
              ),
              Group(
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                        formKey: _formKey,
                        formItem:
                        _erpDeptCode != '2714' ?[FormItem(
                            type: 'input',
                            labelWidth: 90,
                            labelText: '物料编号',
                            placeholder: '请扫物料编号',
                            focusNode: _firstFocusNode,
                            onEntry: (String value){
                              setValue('_code', value);
                              confirm();
                            },
                            filedName: 'code',
                            value: _code,
                            icon: const Icon(Icons.qr_code_scanner_rounded),
                            iconOnTap: scan,
                            // onChange: (value) => setValue('_code', value),
                            rules: const {'code': [{'required': true, 'message': '物料编号不能为空'}]},
                          )] : [
                            FormItem(
                              type: 'input',
                              labelWidth: 90,
                              labelText: '出库单号',
                              placeholder: '请扫出库单号',
                              focusNode: _firstFocusNode,
                              onEntry: (String value) => {
                                FocusScope.of(context).requestFocus(_secondFocusNode)
                              },
                              filedName: 'billNo',
                              value: _billNo,
                              icon: const Icon(Icons.qr_code_scanner_rounded),
                              iconOnTap: scan,
                              onChange: (value) => setValue('_billNo', value),
                              rules: const {'billNo': [{'required': true, 'message': '出库单号不能为空'}]},
                            ),
                            FormItem(
                              type: 'input',
                              labelWidth: 90,
                              labelText: '物料编号',
                              placeholder: '请扫物料编号',
                              focusNode: _secondFocusNode,
                              onEntry: (String value)=>{
                                painting()
                              },
                              filedName: 'code',
                              value: _code,
                              icon: const Icon(Icons.qr_code_scanner_rounded),
                              iconOnTap: scan,
                              onChange: (value) => setValue('_code', value),
                              rules: const {'code': [{'required': true, 'message': '物料编号不能为空'}]},
                            ),
                          ],
                    ),
                    // Padding(
                    //   padding: const EdgeInsets.only(top: 10, right: 10, bottom: 10),
                    //   child: Row(
                    //       mainAxisAlignment: MainAxisAlignment.end,
                    //       children: [
                    //         Button(
                    //           label: '清空',
                    //           icon: Icons.delete_forever,
                    //           onPressed: clear,
                    //           fontColor: Colors.black,
                    //           backgroundColor: Colors.white,
                    //           borderColor: const Color.fromARGB(255, 133, 133, 133),
                    //         ),
                    //       ]
                    //   ),
                    // ),
                  ],
                ),
              ),
              Expanded(
                child: ListContainer(
                  // title: '物料信息',
                  length: _list.length,
                  actions: [
                    SlidActions(
                        onPressed: remove,
                        label: '删除',
                        icon: Icons.delete
                    )
                  ],
                  children: (index){
                    return [
                      ListTitle(context: context, label: _list[index]['itemName'],),
                      Horizontal(
                          items: [
                            HorizontalItem(
                              label: '编号：',
                              value: _list[index]['itemCode'],
                            ),
                            HorizontalItem(
                              child: Container(
                                height: 40,
                                child: Number(
                                  subtraction: ()=>{subtraction(index)},
                                  add: ()=>{add(index)},
                                  entry: (String value)=>{changeNumber(index, value)},
                                  value: _list[index]['itemQty'],
                                ),
                              ),
                            )
                          ]
                      ),

                    ];
                  },
                ),
              )
            ],
          )
      ),
    );
  }

}